package UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UDPClient {
    private DatagramSocket socket = new DatagramSocket();
    private String serverIP;
    private int serverPort;

    public UDPClient(String ip, int port) throws SocketException {
        this.serverIP = ip;
        this.serverPort = port;
    }

    public void start() throws IOException {
        System.out.println("客户端启动！");
        Scanner scanner = new Scanner(System.in);

        while(true){
            System.out.print("-> ");
            String input = scanner.nextLine();
            DatagramPacket requestPacket = new DatagramPacket(input.getBytes(),
                    input.getBytes().length, InetAddress.getByName(serverIP), serverPort);

            socket.send(requestPacket);
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            String res = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.println("服务器响应：" + res);
        }

    }

    public static void main(String[] args) throws IOException {
        UDPClient client = new UDPClient("127.0.0.1", 9090);
        client.start();
    }
}
